/**
 * Ingenius-Group S.A.S
 *
 * Project: SAU
 * File: TabMenu.java
 * Date: 12/03/2011
 */

package com.ingenius.sau.client.view.widgets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.widget.Html;
import com.google.gwt.user.client.Element;

/**
 * Class <strong>TabMenu</strong>
 * 
 * @author Jesus David
 * @version 0.1
 */
public class TabMenu extends Html {

	static String TEMPLATE = "<li><a href='#%s' class='%s' onmousedown='event.preventDefault()'>%s</a></li>";

	private List<String> keys;
	private List<String> urls;
	private Map<String, Object> items;

	private int currentIndex = -1;

	public TabMenu() {
		keys = new ArrayList<String>();
		urls = new ArrayList<String>();
		items = new HashMap<String, Object>();
	}

	public void addItem(String itemText, String url) {
		if (!keys.contains(itemText)) {
			keys.add(itemText);
			urls.add(url);
			items.put(itemText, createMenuItem(itemText, url, ""));
		}
	}

	public void setCurrent(String url) {
		int index = urls.indexOf(url);

		if (index >= 0) {
			if (currentIndex >= 0) {
				String text = keys.get(currentIndex);
				String old = urls.get(currentIndex);
				items.put(text, createMenuItem(text, old, ""));
			}
			String text = keys.get(index);
			items.put(text, createMenuItem(text, url, "current"));
			currentIndex = index;
		}
		refresh();
	}

	private String createMenuItem(String text, String url, String style) {
		return StringUtil.format(TEMPLATE, url, style, text);
	}

	public void refresh() {
		String menu = "<ul>";
		for (String key : keys) {
			menu += items.get(key);
		}
		menu += "</u>";
		setHtml(menu);
	}

	@Override
	public void render(Element target) {
		super.render(target);
		refresh();
	}

}
